package com.veal98.tree;

import com.veal98.bean.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class CountCompleteTreeNodes_222 {

    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }

        // 二叉树节点个数
        int res = 0;

        Queue<TreeNode> queue = new LinkedList<>();
        // 根节点入队
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i ++) {
                TreeNode cur = queue.poll();
                res ++;

                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }

        return res;
    }

    public int countNodes2(TreeNode root) {
        // 递归出口
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }

        int leftSize = countNodes2(root.left);
        int rightSize = countNodes2(root.right);

        return leftSize + rightSize + 1;
    }

    public int countNodes3(TreeNode root) {
        if (root == null) {
            return 0;
        }

        TreeNode left = root.left;
        TreeNode right = root.right;

        int leftHeight = 0;
        int rightHeight = 0;

        while (left != null) {
            left = left.left;
            leftHeight ++;
        }
        while (right != null) {
            right = right.right;
            rightHeight ++;
        }

        if (leftHeight == rightHeight) {
            return (2 << leftHeight) - 1;
        }

        return countNodes3(root.left) + countNodes3(root.right) + 1;
    }

}
